using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerSwapInput : MonoSingleton<PlayerSwapInput>
{
  [SerializeField]
  private FieldEngine _fieldEngine;
  [SerializeField]
  private FieldView _fieldView;
  private Vector2Int m_startGridPosition;
  private Vector2 m_startScreenPosition;

  private bool m_hasDown;

  public void OnPointerDown(Vector2Int gridPosition, Vector2 screenPos) {
    m_hasDown = true;
    m_startGridPosition = gridPosition;
    m_startScreenPosition = screenPos;
  }

  public void OnPointerUp(Vector2 screenPos) {
    if(!m_hasDown)
    {
      return;
    }

    m_hasDown = false;
    var dir = GetDirection(m_startScreenPosition, screenPos);
    var holder = _fieldView.GetRenderHolder();
    var resolver = new PlayerSwapResolver(m_startGridPosition, m_startGridPosition + dir, holder);
    _fieldEngine.TriggerResolve(resolver);
  }

  private Vector2Int GetDirection(Vector2 start, Vector2 end) {
    var to = end - start;
    Vector2Int result = new();
    if (Mathf.Abs(to.x) > Mathf.Abs(to.y))
    {
      if (to.x > 0)
      {
        result = Vector2Int.right;
      } else
      {
        result = Vector2Int.left;
      }
    } else
    {
      if (to.y > 0)
      {
        result = Vector2Int.up;
      } else
      {
        result = Vector2Int.down;
      }
    }
    return result;
  }

  private void Update() {
    // test code
    if (Input.GetMouseButtonUp(0))
    {
      OnPointerUp(Camera.main.ScreenToWorldPoint(Input.mousePosition));
    }
  }
}
